<template>
	<div class="admin-container">
		<!-- 搜索栏 -->
		<div class="search-bar">
			<el-row :gutter="20">
				<el-col :span="4">
					<el-input v-model="searchParams.name" placeholder="请输入商品名称" clearable
						@keyup.enter.native="searchByName">
					</el-input>
				</el-col>
				<el-col :span="3">
					<el-select v-model="searchParams.pettypeName" placeholder="请选择宠物类型" clearable
						@keyup.enter.native="searchByPettypeName" @change="searchByPettypeName">
						<el-option v-for="item in pettypeOptions" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-col>
				<el-col :span="17">
					<el-button type="primary" @click="searchByName">查询商品名称</el-button>
					<!-- <el-button type="primary" @click="searchByPettypeName">查询宠物类型</el-button> -->
					<el-button type="success" @click="showAddDialog">新增</el-button>
				</el-col>
			</el-row>
		</div>
		<div class="operation-bar">
			<el-button size="mini" @click="batchMarkPaid">有库存</el-button>
			<el-button size="mini" @click="batchMarkShipped">无库存</el-button>
			<el-button size="mini" @click="batchrecommend">推荐</el-button>
			<el-button size="mini" @click="batchrecommend2">不推荐</el-button>
			<el-button size="mini" @click="batchDelete">删除</el-button>
		</div>
		<!-- 信息展示区 -->
		<div class="table-container">
			<el-table :data="tableData" style="width: 100%" border v-if="tableData.length > 0" @selection-change="handleSelectionChange">
			  <el-table-column type="selection" width="55"></el-table-column>
			
				<el-table-column prop="name" label="商品名称" width="180"></el-table-column>
				<el-table-column label="宠物图片" width="80">
					<template slot-scope="scope">
						<el-image style="width: 50px; height: 50px;" :src="scope.row.img" fit="cover"></el-image>
					</template>
				</el-table-column>
				<el-table-column prop="description" label="描述"></el-table-column>
				<el-table-column prop="original_price" label="原价" width="80"></el-table-column>
				<el-table-column prop="discount_price" label="折扣价" width="80"></el-table-column>
				<el-table-column prop="pettypeName" label="宠物类型" width="80"></el-table-column>
				<el-table-column prop="stock" label="库存" width="80"></el-table-column>
				<el-table-column prop="state" label="状态" width="80"></el-table-column>
				<el-table-column prop="recommend" label="状态" width="80"></el-table-column>
				<el-table-column prop="create_time" label="创建时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.create_time) }}
					</template>
				</el-table-column>
				<el-table-column prop="update_time" label="更新时间">
					<template slot-scope="scope">
						{{ formatDate(scope.row.update_time) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180">
					<template slot-scope="scope">
						<el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
						<el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div v-else class="no-data">
				<p>没有找到匹配的数据</p>
			</div>
		</div>
		<!-- 分页组件 -->
		<div class="pagination-container">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page.sync="currentPage" :page-size.sync="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="allData.length">
			</el-pagination>
		</div>
		<!-- 编辑对话框 -->
		<el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="30%">
			<el-form :model="currentRow" :rules="editRules" ref="editForm">
				<el-form-item label="商品名称" prop="name">
					<el-input v-model="currentRow.name"></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="currentRow.description"></el-input>
				</el-form-item>
				<el-form-item label="原价" prop="original_price">
					<el-input v-model="currentRow.original_price"></el-input>
				</el-form-item>
				<el-form-item label="折扣价" prop="discount_price">
					<el-input v-model="currentRow.discount_price"></el-input>
				</el-form-item>
				<el-form-item label="宠物类型" prop="pettype_id">
					<el-select v-model="currentRow.pettype_id" placeholder="请选择宠物类型">
						<el-option v-for="item in pettypeOptions" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="库存" prop="stock">
					<el-input v-model="currentRow.stock"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="state">
				    <el-select v-model="currentRow.state" placeholder="请选择状态">
				        <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value">
				        </el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="状态" prop="recommend">
				    <el-select v-model="currentRow.recommend" placeholder="请选择状态">
				        <el-option v-for="item in stateOptions2" :key="item.value" :label="item.label" :value="item.value">
				        </el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="图片链接" prop="img">
					<el-upload class="avatar-uploader" action="http://localhost:8887/upload" :show-file-list="false"
						:on-success="handleImageSuccess" :before-upload="beforeImageUpload"
						:http-request="customUpload">
						<el-image v-if="currentRow.img" :src="currentRow.img" class="avatar"></el-image>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleUpdate">更新</el-button>
			</span>
		</el-dialog>
		<!-- 新增对话框 -->
		<el-dialog title="新增商品" :visible.sync="addDialogVisible" width="30%">
			<el-form :model="addProduct" :rules="addRules" ref="addForm">
				<el-form-item label="商品名称" prop="name">
					<el-input v-model="addProduct.name"></el-input>
				</el-form-item>
				<el-form-item label="描述" prop="description">
					<el-input v-model="addProduct.description"></el-input>
				</el-form-item>
				<el-form-item label="原价" prop="original_price">
					<el-input v-model="addProduct.original_price"></el-input>
				</el-form-item>
				<el-form-item label="折扣价" prop="discount_price">
					<el-input v-model="addProduct.discount_price"></el-input>
				</el-form-item>
				<el-form-item label="宠物类型" prop="pettype_id">
					<el-select v-model="addProduct.pettype_id" placeholder="请选择宠物类型">
						<el-option v-for="item in pettypeOptions" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="库存" prop="stock">
					<el-input v-model="addProduct.stock"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="state">
				    <el-select v-model="addProduct.state" placeholder="请选择状态">
				        <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value">
				        </el-option>
				    </el-select>
				</el-form-item>
				<el-form-item label="图片链接" prop="img">
					<el-upload class="avatar-uploader" action="http://localhost:8887/upload" :show-file-list="false"
						:on-success="handleImageSuccess" :before-upload="beforeImageUpload"
						:http-request="customUpload">
						<el-image v-if="addProduct.img" :src="addProduct.img" class="avatar"></el-image>
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="handleAdd">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>
<script>
	import axios from 'axios';
	import {
		Input,
		Row,
		Col,
		Button,
		Table,
		TableColumn,
		Dialog,
		Form,
		FormItem,
		Pagination,
		Message,
		Image as ElImage,
		Upload,
		Select,
		Option
	} from 'element-ui';

	export default {
		name: 'ProductTable',
		components: {
			'el-input': Input,
			'el-row': Row,
			'el-col': Col,
			'el-button': Button,
			'el-table': Table,
			'el-table-column': TableColumn,
			'el-dialog': Dialog,
			'el-form': Form,
			'el-form-item': FormItem,
			'el-pagination': Pagination,
			'el-image': ElImage,
			'el-upload': Upload,
			'el-select': Select,
			'el-option': Option
		},
		data() {
			return {
				stateOptions: [ 
				            { label: '有库存', value: '有库存' },
				            { label: '无库存', value: '无库存' }
				        ],
						stateOptions2: [
						            { label: '推荐', value: '推荐' },
						            { label: '不推荐', value: '不推荐' }
						        ],
				allData: [], // 存储所有数据
				tableData: [], // 存储当前页的数据
				searchParams: {
					name: '',
					pettypeName: '', // 宠物类型搜索参数
				},
				selectedRows: [], // 存储选中的行
				pettypeOptions: [], // 宠物类型选项
				editDialogVisible: false,
				currentRow: {
					name: '',
					description: '',
					original_price: '',
					discount_price: '',
					pettype_id: '',
					stock: '',
					state: '',
					recommend: '',
					img: '',
					id: null
				},
				addDialogVisible: false,
				addProduct: {
					name: '',
					description: '',
					original_price: '',
					discount_price: '',
					pettype_id: '',
					stock: '',
					state: '',
					img: '',
				},
				editRules: {
					name: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}],
					description: [{
						required: true,
						message: '请输入描述',
						trigger: 'blur'
					}],
					original_price: [{
						required: true,
						message: '请输入原价',
						trigger: 'blur'
					}],
					discount_price: [{
						required: false,
						message: '请输入折扣价',
						trigger: 'blur'
					}],
					pettype_id: [{
						required: true,
						message: '请输入宠物类型',
						trigger: 'blur'
					}],
					stock: [{
						required: true,
						message: '请输入库存',
						trigger: 'blur'
					}],
					state: [{
					        required: true,
					        message: '请选择状态',
					        trigger: 'change'
					    }],
						recommend: [{
						required: true,
						message: '请输入推荐状态',
						trigger: 'blur'
					}],
					img: [{
						required: true,
						message: '请输入图片链接',
						trigger: 'blur'
					}],
				},
				addRules: {
					name: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}],
					description: [{
						required: true,
						message: '请输入描述',
						trigger: 'blur'
					}],
					original_price: [{
						required: true,
						message: '请输入原价',
						trigger: 'blur'
					}],
					discount_price: [{
						required: false,
						message: '请输入折扣价',
						trigger: 'blur'
					}],
					pettype_id: [{
						required: true,
						message: '请输入宠物类型',
						trigger: 'blur'
					}],
					stock: [{
						required: true,
						message: '请输入库存',
						trigger: 'blur'
					}],
					state: [{
					        required: true,
					        message: '请选择状态',
					        trigger: 'change'
					    }],
					img: [{
						required: true,
						message: '请输入图片链接',
						trigger: 'blur'
					}],
				},
				currentPage: 1,
				pageSize: 10,
			};
		},
		created() {
			this.fetchData();
			this.fetchPettypeData();
		},
		methods: {
			fetchData() {
				const token = localStorage.getItem('Authorization');
				if (!token) {
					this.$message.error('未授权访问');
					return;
				}
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Product/findAll', {
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
						} else {
							this.$message.error('获取数据失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			fetchPettypeData() {
				const token = localStorage.getItem('Authorization');
				if (!token) {
					this.$message.error('未授权访问');
					return;
				}
				const headers = {
					'Content-Type': 'application/json',
					'Authorization': token
				};
				axios.get('http://localhost:8887/Pettype/findAll', {
						headers
					})
					.then(response => {
						if (response.data.code === 200) {
							this.pettypeOptions = response.data.data;
						} else {
							this.$message.error('获取宠物类型数据失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			formatDate(value) {
				const date = new Date(value);
				return new Intl.DateTimeFormat('zh-CN', {
					year: 'numeric',
					month: '2-digit',
					day: '2-digit',
					hour: '2-digit',
					minute: '2-digit',
					second: '2-digit',
					hour12: false
				}).format(date);
			},
			searchByName() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token,
				};
				axios.get('http://localhost:8887/Product/selectname', {
						headers,
						params: {
							name: this.searchParams.name
						}
					})
					.then(response => {
						if (response.data.code === 200 && response.data.data.length > 0) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
							this.currentPage = 1; // 重置当前页为 1
						} else {
							this.$message.error(response.data.message || '未找到匹配的商品');
							this.tableData = []; // 清空表格数据
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			searchByPettypeName() {
				const token = localStorage.getItem('Authorization');
				const headers = {
					'Content-Type': 'application/x-www-form-urlencoded',
					'Authorization': token,
				};
				axios.get('http://localhost:8887/Product/selectpettype_id', {
						headers,
						params: {
							pettype_id: this.searchParams.pettypeName
						}
					})
					.then(response => {
						if (response.data.code === 200 && response.data.data.length > 0) {
							this.allData = response.data.data;
							this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this
								.currentPage * this.pageSize);
							this.currentPage = 1; // 重置当前页为 1
						} else {
							this.fetchData();
							this.$message.error(response.data.message || '未找到匹配的宠物类型');
							this.tableData = []; // 清空表格数据
						}
					})
					.catch(error => {
						console.error('请求失败:', error);
						this.$message.error('请求失败，请检查网络或联系管理员');
					});
			},
			handleEdit(row) {
				if (row) {
					this.currentRow = {
						...row
					};
					this.editDialogVisible = true;
				} else {
					console.error('Error: Row data is null');
				}
			},
			handleDelete(id) {
				this.$confirm('确认删除这条记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/x-www-form-urlencoded',
						'Authorization': token
					};
					axios.post('http://localhost:8887/Product/delete', {
							id
						}, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success('删除成功');
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error('删除失败: ' + response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消删除');
				});
			},
			// getPetTypeIdByName(pettypeName) {
			//             let found = this.pettypeOptions.find(option => option.name === pettypeName);
			//             return found ? found.id : null;
			//         },
			handleUpdate() {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						const token = localStorage.getItem('Authorization');
						const headers = {
							'Content-Type': 'application/json',
							'Authorization': token
						};
						// let pettypeId = this.getPetTypeIdByName(this.currentRow.pettypeName);
						axios.post('http://localhost:8887/Product/update', 
							this.currentRow,
							// pettype_id: pettypeId, 
						 {
								headers
							})
							.then(response => {
								if (response.data.code === 200) {
									this.$message.success('更新成功');
									this.editDialogVisible = false;
									this.fetchData(); // 重新加载数据
								} else {
									this.$message.error('更新失败: ' + response.data.message);
								}
							})
							.catch(error => {
								console.error('请求失败:', error);
								this.$message.error('请求失败，请检查网络或联系管理员');
							});
					} else {
						this.$message.error('表单验证失败');
					}
				});
			},
			handleAdd() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						const token = localStorage.getItem('Authorization');
						const headers = {
							'Content-Type': 'application/json',
							'Authorization': token
						};
						axios.post('http://localhost:8887/Product/add',
							this.addProduct,
							// pettype_id: this.addProduct.pettypeName, 
						 {
								headers
							})
							.then(response => {
								if (response.data.code === 200) {
									this.$message.success('新增成功');
									this.addDialogVisible = false;
									this.fetchData(); // 重新加载数据
								} else {
									this.$message.error('新增失败: ' + response.data.message);
								}
							})
							.catch(error => {
								console.error('请求失败:', error);
								this.$message.error('请求失败，请检查网络或联系管理员');
							});
					} else {
						this.$message.error('表单验证失败');
					}
				});
			},
			showAddDialog() {
				this.addDialogVisible = true;
				this.addProduct = {
					name: '',
					description: '',
					original_price: '',
					discount_price: '',
					pettypeName: '',
					pettype_id: '',
					stock: '',
					state: '',
					img: '',
				};
			},
			handleSizeChange(newSize) {
				this.pageSize = newSize;
				this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
					.pageSize);
			},
			handleCurrentChange(newPage) {
				this.currentPage = newPage;
				this.tableData = this.allData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this
					.pageSize);
			},
			beforeImageUpload(file) {
				const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
				}
				const isLt2M = file.size / 1024 / 1024 < 2;
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},
			customUpload(file) {
				const formData = new FormData();
				formData.append('file', file.file);
				axios.post('http://localhost:8887/upload', formData, {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				}).then(response => {
					if (response.data.code === 200) {
						this.handleImageSuccess(response.data.data);
					} else {
						this.$message.error('上传失败: ' + response.data.message);
					}
				}).catch(error => {
					console.error('请求失败:', error);
					this.$message.error('请求失败，请检查网络或联系管理员');
				});
			},
			handleImageSuccess(imageUrl) {
				if (this.addDialogVisible) {
					this.addProduct.img = imageUrl;
				} else {
					this.currentRow.img = imageUrl;
				}
			},
			batchMarkPaid() {
				this.batchUpdateStatus('有库存');
			},
			batchMarkShipped() {
				this.batchUpdateStatus('无库存');
			},
			batchDelete() {
				this.confirmAndDelete();
			},
			handleSelectionChange(val) {
			    this.selectedRows = val;
			  },
			batchUpdateStatus(newState) {
				this.$confirm('确认执行此批量操作吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const ids = this.selectedRows.map(row => row.id);
					if (ids.length === 0) {
						this.$message.warning('请选择要操作的行');
						return;
					}
					const payload = {
						ids: ids,
						state: newState
					};
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/json',
						'Authorization': token
					};
					axios.post('http://localhost:8887/Product/batchUpdateStatus', payload, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success(response.data.message);
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error(response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消操作');
				});
			},
			batchrecommend() {
				this.batchUpdateRecommend('推荐');
			},
			batchrecommend2() {
				this.batchUpdateRecommend('不推荐');
			},
			batchUpdateRecommend(recommend) {
				this.$confirm('确认执行此批量操作吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const ids = this.selectedRows.map(row => row.id);
					if (ids.length === 0) {
						this.$message.warning('请选择要操作的行');
						return;
					}
					const payload = {
						ids: ids,
						recommend: recommend
					};
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/json',
						'Authorization': token
					};
					axios.post('http://localhost:8887/Product/batchUpdateRecommend', payload, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success(response.data.message);
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error(response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消操作');
				});
			},
			confirmAndDelete() {
				this.$confirm('确认执行此批量操作吗?', '提示', {
					type: 'warning'
				}).then(() => {
					const ids = this.selectedRows.map(row => row.id);
					if (ids.length === 0) {
						this.$message.warning('请选择要操作的行');
						return;
					}
					const payload = {
						ids: ids,
					};
					const token = localStorage.getItem('Authorization');
					const headers = {
						'Content-Type': 'application/json',
						'Authorization': token
					};
					axios.post('http://localhost:8887/Product/admindelete', payload, {
							headers
						})
						.then(response => {
							if (response.data.code === 200) {
								this.$message.success(response.data.message);
								this.fetchData(); // 重新加载数据
							} else {
								this.$message.error(response.data.message);
							}
						})
						.catch(error => {
							console.error('请求失败:', error);
							this.$message.error('请求失败，请检查网络或联系管理员');
						});
				}).catch(() => {
					this.$message.info('已取消操作');
				});
			},
		}
	};
</script>
<style scoped>
	.admin-container {
		padding: 20px;
		max-width: 100%;
		overflow-x: auto;
	}

	.search-bar {
		margin-bottom: 20px;
	}

	.search-bar .el-row {
		display: flex;
		justify-content: space-between;
	}

	.search-bar .el-button {
		margin-left: 10px;
	}

	.table-container {
		margin-top: 20px;
		overflow-x: auto;
	}

	.no-data {
		text-align: center;
		padding: 20px;
	}

	.pagination-container {
		margin-top: 20px;
		text-align: left;
	}

	.dialog-footer {
		text-align: right;
	}

	.el-dialog__body {
		padding: 20px;
	}

	.el-form-item {
		margin-bottom: 20px;
	}

	.el-form-item__label {
		font-weight: bold;
	}

	.el-button--primary {
		background-color: #13ce66;
		border-color: #13ce66;
	}

	.el-button--primary:hover {
		background-color: #11b55e;
		border-color: #11b55e;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 100px;
		height: 100px;
		line-height: 100px;
		text-align: center;
	}

	.avatar {
		width: 100px;
		height: 100px;
		display: block;
	}
</style>